package com.itlong.cloud.rabbitmq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.POJO.PO.UserLoginLogPO;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.service.IUserLoginLogService;
import com.itlong.cloud.utils.node.JsonUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * <desc>
 *     保存用户登录日志消息队列消费者
 * </desc>
 *
 * @createDate 2018/04/28
 */
@Component
public class UserLoginLogConsumer {

    private static final Logger LOG = LoggerFactory.getLogger(UserLoginLogConsumer.class);

    @Autowired
    private IUserLoginLogService iUserLoginLogService;


    /**
     * <desc>
     *     保存登录日志业务指令消费过程
     * </desc>
     *
     * @param message 监听到的业务消息
     * @param channel 频道
     * @author wangzhi
     * @createDate 2018/05/02
     */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_USER_LOGIN_LOG_SAVE_QUEUE)
    public void process(Message message, Channel channel) throws IOException {
        byte[] body = message.getBody();
        try {
            TimeTaskDeadMessageQueuePO timeTaskDeadMessageQueuePO = JsonUtil.toObject(new String(body),
                    TimeTaskDeadMessageQueuePO.class);
            String content = timeTaskDeadMessageQueuePO.getMessageContent();
            JSONObject jsdata = JSONObject.parseObject(content);
            UserLoginLogPO userLoginLogPO = jsdata.getObject("data", UserLoginLogPO.class);

//            System.err.println(userLoginLogPO.getRealName());

            iUserLoginLogService.save(userLoginLogPO);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            LOG.error("【RabbitMQ_保存登录日志消费端】:消费异常",e);
        } finally {
            //手动确认消息消费成功。
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
    }

}
